<template>
  <div class="app-container">
    <PlatformHeader />
    <div class="main-container" :style="{ height: `calc(100vh - 72px)` }">
      <!-- 左侧面板 - 使用绝对定位 -->
      <div
        class="left-panel"
        :class="{ 'hidden': leftPaneSize === 0 }"
        :style="{ width: `${leftPaneSize}%` }"
      >
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入机构名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </div>

      <!-- 右侧主内容区 - 占满宽度 -->
      <div class="right-panel">
        <!-- 显示/隐藏左侧面板的按钮 -->
        <button
          class="toggle-btn"
          @click="toggleLeftPane"
          :style="{ left: leftPaneSize === 0 ? '10px' : `${leftPaneSize}%` }"
        >
          <i class="el-icon-s-fold" v-if="leftPaneSize > 0"></i>
          <i class="el-icon-s-unfold" v-else></i>
        </button>

        <el-col style="flex:1;display: flex;flex-direction: column">
          <el-form
            :model="form"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="90px"
            :rules="formRules"
            class="custom-form"
            style="padding-top: 10px;box-sizing: border-box;padding-left: 16px"
          >
            <el-form-item  prop="deptId">
              <el-input
                v-model="selectedNodeInfo"
                placeholder="请从左侧选择机构"
                readonly
                clearable
                style="width: 220px;background-color: transparent;"
                @focus="handleInputFocus"
              />
            </el-form-item>

            <el-form-item  prop="dateRange">
              <el-date-picker
                popper-class="custom-select-dropdown"
                v-model="form.dateRange"
                style="width: 260px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                @change="handleDateChange"
              />
            </el-form-item>

            <el-form-item label="人群分类" style="display: none">
              <el-select
                v-model="form.population"
                placeholder="请选择群体"
                clearable
                @change="handlePopulationChange"
                style="width: 220px"
              >
                <el-option
                  v-for="item in populationOptions"
                  :key="item.id"
                  :label="item.peopletypename"
                  :value="item.beizhu"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="测试项目" style="display: none">
              <el-select
                v-model="form.testItem"
                placeholder="请先选择群体"
                clearable
                :disabled="!form.population"
                style="width: 220px"
                @change="handleTestItemChange"
              >
                <el-option
                  v-for="item in testItemOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                :disabled="!isFormValid"
                class="search-btn action-btn"
              >查询</el-button>
              <el-button class="reset-btn action-btn" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <div v-if="showCharts" class="chart-container">
            <!-- 左右结构布局 -->
            <div style="height: 50px;line-height: 50px;text-align:center;font-size: 28px;font-weight: bold;margin-bottom: 10px;margin-top: -10px;color: #e6e6e6">
              国民体质{{ selectedPeopleType }}--{{ currentTestItemLabel }}
            </div>
            <el-row style="flex:1;display: flex;justify-content: space-between;">
              <!-- 左侧：合格率图表 (宽度50%) -->
              <el-col :span="11" style="height: 100%; padding-right: 10px;">
                <div class="chart-wrapper full-height">
                  <div class="chart-title">评价等级占比</div>
                  <div v-show="showCharts" ref="passRateChart" class="chart"></div>
                </div>
              </el-col>

              <!-- 右侧：合并统计图表 (宽度50%) -->
              <el-col :span="11" style="height: 100%; padding-left: 10px;">
                <div class="chart-wrapper full-height">
                  <div class="chart-title">评价等级人数统计</div>
                  <div v-show="showCharts" ref="combinedChart" class="chart"></div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <div class="indicatorbtm" style="height: 57px;width:100%;display: flex;">
          <div id='leftitem' style=" margin-top: -20px;flex: 1;height: 100%;display: flex;justify-content: space-around;align-items: flex-end;padding-right: 20px;">
            <div
              v-for="item in leftTestItems"
              :key="item.value"
              class="test-item"
              :class="{ 'active': form.testItem === item.value }"
              :style="{ backgroundImage: `url(${getItemImage(item.value, form.testItem === item.value)})` }"
              @click="handleTestItemClick(item.value)"
              @mouseover="showTooltip($event, item.label)"
              @mouseout="hideTooltip"
            ></div>
          </div>
          <div id='getPeopletypelist' style="width: 700px;height: 100%;padding: 0px 63px;display: flex;justify-content: space-evenly;align-items: flex-end">
            <div
              class="people-type-item"
              @click="handlePeopleTypeClick('幼儿')"
              :class="{ 'active': selectedPeopleType === '幼儿' }"
              :style="{ backgroundImage: `url(${getPeopleTypeImage('幼儿')})` }"
            ></div>
            <div
              class="people-type-item"
              @click="handlePeopleTypeClick('成年')"
              :class="{ 'active': selectedPeopleType === '成年' }"
              :style="{ backgroundImage: `url(${getPeopleTypeImage('成年')})` }"
            ></div>
            <div
              class="people-type-item"
              @click="handlePeopleTypeClick('老年')"
              :class="{ 'active': selectedPeopleType === '老年' }"
              :style="{ backgroundImage: `url(${getPeopleTypeImage('老年')})` }"
            ></div>
          </div>
          <div id='rightitem' style=" margin-top: -20px;flex: 1;height: 100%;display: flex;justify-content: space-around;align-items: flex-end;padding-left: 20px;">
            <div
              v-for="item in rightTestItems"
              :key="item.value"
              class="test-item"
              :class="{ 'active': form.testItem === item.value }"
              :style="{ backgroundImage: `url(${getItemImage(item.value, form.testItem === item.value)})` }"
              @click="handleTestItemClick(item.value)"
              @mouseover="showTooltip($event, item.label)"
              @mouseout="hideTooltip"
            ></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 工具提示 -->
    <div v-if="tooltip.visible"
         class="test-item-tooltip"
         :style="{ top: tooltip.y + 'px', left: tooltip.x + 'px' }">
      {{ tooltip.text }}
    </div>
  </div>
</template>

<script>
import { deptTreeSelect } from "@/api/system/user";
import PlatformHeader from '../../../components/PlatformHeader/index.vue';
import {
  getPeopletypelist,
  getItemelist,
  getItemevalution,
} from "../../../api/monitormanage/indicator";
import * as echarts from 'echarts';

export default {
  name: "IndicatorStatistics",
  components: {
    PlatformHeader
  },
  data() {
    const validateDateRange = (rule, value, callback) => {
      if (!value || value.length !== 2) {
        callback(new Error('请选择完整的日期范围'));
      } else {
        callback();
      }
    };
   // 获取默认日期范围
    const getDefaultDateRange = () => {
      const today = new Date();
      const currentYear = today.getFullYear();
      const startDate = `${currentYear}-01-01`;
      const endDate = today.toISOString().split('T')[0];
      return [startDate, endDate];
    };

    const defaultRange = getDefaultDateRange();
    return {
      leftPaneSize: 0, // 左侧面板占16%宽度
      form: {
        deptId: undefined,
        dateRange: defaultRange,
        population: undefined,
        testItem: undefined,
        starttime: defaultRange[0],
        endtime: defaultRange[1],
        ageMin: undefined,
        ageMax: undefined
      },
      loading: true,
      showSearch: true,
      showCharts: false,
      deptOptions: undefined,
      deptName: undefined,
      passRateChart: null,
      combinedChart: null,
      // 日期选择器配置
      pickerOptions: {
        disabledDate: (time) => {
          // 如果没有选择开始日期或者已经清除了选择，只禁用未来日期
          if (!this.startYear) {
            return time.getTime() > Date.now();
          }

          // 如果已经选择了开始日期，限制只能选择同一年份
          const timeYear = time.getFullYear();
          return time.getTime() > Date.now() || timeYear !== this.startYear;
        },
        onPick: ({ maxDate, minDate }) => {
          if (minDate) {
            // 保存选中的开始日期年份
            this.startYear = minDate.getFullYear();
          } else {
            // 如果没有选择日期，清除年份限制
            this.startYear = null;
          }
        },
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        },{
          text: '本年至今', //
          onClick(picker) {
            const end = new Date();
            const start = new Date(end.getFullYear(), 0, 1);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      formRules: {
        deptId: [
          { required: true, message: '请选择机构', trigger: 'change' }
        ],
        dateRange: [
          { validator: validateDateRange, trigger: 'change' }
        ]
      },
      selectedNodeInfo: '',
      populationOptions: [],
      testItemOptions: [],
      leftTestItems: [], // 左侧显示的测试项目
      rightTestItems: [], // 右侧显示的测试项目
      chartData: {
        peopleData: {
          male: 0,
          female: 0,
          total: 0
        },
        passRateData: {
          male: 0,
          female: 0,
          total: 0
        },
        scoreDistributionData: {
          male: {
            excellent: 0,
            good: 0,
            pass: 0,
            fail: 0
          },
          female: {
            excellent: 0,
            good: 0,
            pass: 0,
            fail: 0
          },
          total: {
            excellent: 0,
            good: 0,
            pass: 0,
            fail: 0
          }
        }
      },
      resizeObservers: {},
      debounceTimer: null,
      hasGoodLevel: true,
      selectedPeopleType: '幼儿', // 默认选中幼儿
      tooltip: {
        visible: false,
        x: 0,
        y: 0,
        text: ''
      },
      autoQueryTriggered: false,
      queryTimer: null,
      lastQueryParams: null,
      windowResizeHandler: null // 新增窗口大小变化处理器
    };
  },
  computed: {
    isFormValid() {
      return this.form.deptId && this.form.dateRange;
    },
    currentTestItemLabel() {
      const item = this.testItemOptions.find(item => item.value === this.form.testItem);
      return item ? item.label : '';
    },
    allConditionsMet() {
      return (
        this.form.deptId !== undefined &&
        this.form.dateRange && this.form.dateRange.length === 2 &&
        this.form.population !== undefined &&
        this.form.testItem !== undefined
      );
    },
    currentQueryParams() {
      return {
        deptId: this.form.deptId,
        starttime: this.form.starttime,
        endtime: this.form.endtime,
        population: this.form.population,
        testItem: this.form.testItem
      };
    },
    queryParamsChanged() {
      if (!this.lastQueryParams) return true;
      return JSON.stringify(this.currentQueryParams) !== JSON.stringify(this.lastQueryParams);
    }
  },
  watch: {
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    showCharts(val) {
      if (val) {
        this.$nextTick(() => {
          this.initCharts();
        });
      }
    },
    leftPaneSize() {
      this.handlePaneResize();
    },
    form: {
      deep: true,
      handler() {
        if (this.showCharts) {
          this.renderAllCharts();
        }
      }
    },
    allConditionsMet(newVal) {
      if (newVal && this.queryParamsChanged) {
        this.triggerAutoQuery();
      }
    },
    'form.deptId'(newVal) {
      if (newVal && this.allConditionsMet && this.queryParamsChanged) {
        this.triggerAutoQuery();
      }
    },
    'form.dateRange'(newVal) {
      if (newVal && newVal.length === 2 && this.allConditionsMet && this.queryParamsChanged) {
        this.triggerAutoQuery();
      }
    },
    'form.population'(newVal) {
      if (newVal && this.allConditionsMet && this.queryParamsChanged) {
        this.triggerAutoQuery();
      }
    },
    'form.testItem'(newVal) {
      if (newVal && this.allConditionsMet && this.queryParamsChanged) {
        this.triggerAutoQuery();
      }
    }
  },
  methods: {
    /** 获取测试项目对应的图片，增加active参数判断是否使用带a的图片 */
    getItemImage(itemCode, isActive) {
      const baseName = itemCode; // 假设图片名称与itemCode一致
      const suffix = isActive ? 'a' : '';
      return require(`../../assets/images/${baseName}${suffix}.png`);
    },

    /** 获取人群分类对应的图片 */
    getPeopleTypeImage(type) {
      const baseName = type === '幼儿' ? 'young' : type === '成年' ? 'ault' : 'old';
      const suffix = this.selectedPeopleType === type ? 'a' : '';
      return require(`../../assets/images/${baseName}${suffix}.png`);
    },

    /** 触发自动查询 */
    triggerAutoQuery() {
      if (this.queryTimer) {
        clearTimeout(this.queryTimer);
      }

      this.queryTimer = setTimeout(() => {
        if (this.allConditionsMet && this.queryParamsChanged) {
          this.handleQuery();
          this.lastQueryParams = this.currentQueryParams;
        }
      }, 500);
    },

    /** 将测试项目分为左右两组 */
    splitTestItems(items) {
      const totalItems = items.length;
      const splitIndex = Math.ceil(totalItems / 2);

      this.leftTestItems = items.slice(0, splitIndex);
      this.rightTestItems = items.slice(splitIndex);

      // 默认选中左侧第一个项目
      if (this.leftTestItems.length > 0 && !this.form.testItem) {
        this.form.testItem = this.leftTestItems[0].value;
      }
    },

    /** 处理测试项目点击 */
    handleTestItemClick(itemCode) {
      this.form.testItem = itemCode;
    },

    /** 处理测试项目选择变化 */
    handleTestItemChange() {
      this.autoQueryTriggered = false;
    },

    /** 显示工具提示 */
    showTooltip(event, text) {
      this.tooltip = {
        visible: true,
        x: event.clientX + 10,
        y: event.clientY + 10,
        text: text
      };
    },

    /** 隐藏工具提示 */
    hideTooltip() {
      this.tooltip.visible = false;
    },

    /** 切换左侧面板显示/隐藏 */
    toggleLeftPane() {
      if (this.leftPaneSize === 0) {
        this.leftPaneSize = 16;
      } else {
        this.leftPaneSize = 0;
      }
    },

    /** 处理面板大小变化事件 */
    handlePaneResize() {
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer);
      }
      this.debounceTimer = setTimeout(() => {
        this.resizeAllCharts();
      }, 200);
    },

    /** 处理输入框获取焦点事件 */
    handleInputFocus() {
      this.leftPaneSize = 16;
      setTimeout(() => {
        this.resizeAllCharts();
      }, 350);
    },

    /** 初始化图表并添加尺寸监听 */
    initCharts() {
      // 销毁旧图表实例
      if (this.passRateChart) {
        this.passRateChart.dispose();
      }
      if (this.combinedChart) {
        this.combinedChart.dispose();
      }

      // 创建新图表实例
      if (this.$refs.passRateChart) {
        this.passRateChart = echarts.init(this.$refs.passRateChart);
        this.setupResizeObserver('passRateChart', this.$refs.passRateChart);
      }
      if (this.$refs.combinedChart) {
        this.combinedChart = echarts.init(this.$refs.combinedChart);
        this.setupResizeObserver('combinedChart', this.$refs.combinedChart);
      }

      this.renderAllCharts();
    },

    /** 设置 ResizeObserver 监听容器尺寸变化 */
    setupResizeObserver(chartName, container) {
      // 先移除旧的监听器
      if (this.resizeObservers[chartName]) {
        this.resizeObservers[chartName].disconnect();
        delete this.resizeObservers[chartName];
      }

      // 创建新的监听器
      const observer = new ResizeObserver(entries => {
        for (let entry of entries) {
          const { width, height } = entry.contentRect;
          if (width > 0 && height > 0) {
            this.debounceResizeChart(chartName);
          }
        }
      });

      observer.observe(container);
      this.resizeObservers[chartName] = observer;
    },

    /** 防抖调整图表大小 */
    debounceResizeChart(chartName) {
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer);
      }
      this.debounceTimer = setTimeout(() => {
        if (chartName === 'passRateChart' && this.passRateChart) {
          this.passRateChart.resize();
          this.renderPassRateChart(); // 重新渲染饼图以适应新尺寸
        } else if (chartName === 'combinedChart' && this.combinedChart) {
          this.combinedChart.resize();
        }
      }, 100);
    },

    /** 调整所有图表大小 */
    resizeAllCharts() {
      this.passRateChart && this.passRateChart.resize();
      this.combinedChart && this.combinedChart.resize();
    },

    /** 渲染所有图表 */
    renderAllCharts() {
      if (this.passRateChart) {
        this.renderPassRateChart();
      }
      if (this.combinedChart) {
        this.renderCombinedChart();
      }
    },

    /** 查询机构下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        this.form.deptId = response.data[0].id
        this.selectedNodeInfo = response.data[0].label
        // 确保数据加载完成后执行搜索
        // this.$nextTick(() => {
        //   this.handleQuery();
        // });
      });
    },

    /** 获取人群分类列表 */
    getPopulationTypes() {
      getPeopletypelist().then(response => {
        this.populationOptions = response;
        const defaultType = this.populationOptions.find(item => item.peopletypename === '幼儿');
        if (defaultType) {
          this.handlePeopleTypeClick('幼儿');
        }
      });
    },

    /** 处理人群分类点击事件 */
    handlePeopleTypeClick(typeName) {
      this.selectedPeopleType = typeName;

      const selectedPopulation = this.populationOptions.find(item => item.peopletypename === typeName);
      if (selectedPopulation) {
        this.form.population = selectedPopulation.beizhu;
        this.form.ageMin = selectedPopulation.peopleagemin;
        this.form.ageMax = selectedPopulation.peopleagemax;

        this.form.testItem = undefined;
        this.testItemOptions = [];

        getItemelist(selectedPopulation.beizhu).then(response => {
          this.testItemOptions = response.peopletypelist.map(item => ({
            value: item.itemcode,
            label: item.itemname
          }));

          this.splitTestItems(this.testItemOptions);

          if (this.testItemOptions.length > 0) {
            this.$nextTick(() => {
              this.form.testItem = this.testItemOptions[0].value;
            });
          }
        });
      }
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    // 节点单击事件
    handleNodeClick(data) {
      this.form.deptId = data.id;
      this.selectedNodeInfo = `${data.label} `;
      this.leftPaneSize = 0;
      setTimeout(() => {
        this.resizeAllCharts();
      }, 350);
    },

    // 日期范围变化事件
    handleDateChange(val) {
      if (val && val.length === 2) {
        this.form.starttime = val[0];
        this.form.endtime = val[1];
        this.$refs.queryForm.clearValidate(['dateRange']);
      } else {
        this.form.starttime = undefined;
        this.form.endtime = undefined;
        this.form.dateRange = null;
      }
    },

    // 群体选择变化事件
    handlePopulationChange(value) {
      this.form.testItem = undefined;
      this.testItemOptions = [];
      this.leftTestItems = [];
      this.rightTestItems = [];

      const selectedPopulation = this.populationOptions.find(item => item.beizhu === value);
      if (selectedPopulation) {
        this.form.ageMin = selectedPopulation.peopleagemin;
        this.form.ageMax = selectedPopulation.peopleagemax;
        this.selectedPeopleType = selectedPopulation.peopletypename;
      } else {
        this.form.ageMin = undefined;
        this.form.ageMax = undefined;
        this.selectedPeopleType = '';
      }

      if (value) {
        getItemelist(value).then(response => {
          this.testItemOptions = response.peopletypelist.map(item => ({
            value: item.itemcode,
            label: item.itemname
          }));

          this.splitTestItems(this.testItemOptions);

          if (this.testItemOptions.length > 0) {
            this.$nextTick(() => {
              this.form.testItem = this.testItemOptions[0].value;
            });
          }
        });
      }
    },

    /** 渲染合格率图表（修改后的饼图样式） */
    renderPassRateChart() {
      if (!this.$refs.passRateChart) return;

      // 确保图表实例存在
      if (!this.passRateChart) {
        this.passRateChart = echarts.init(this.$refs.passRateChart);
      }

      // 获取数据，设置默认值
      const scoreData = this.chartData.scoreDistributionData || {
        male: { excellent: 0, good: 0, pass: 0, fail: 0 },
        female: { excellent: 0, good: 0, pass: 0, fail: 0 },
        total: { excellent: 0, good: 0, pass: 0, fail: 0 }
      };
      const peopleData = this.chartData.peopleData || { male: 0, female: 0, total: 0 };

      // 准备图表数据
      const prepareData = (data) => {
        const total = data.excellent + data.good + data.pass + data.fail;
        return [
          {
            value: data.excellent,
            name: '优秀',
            itemStyle: { color: '#69af35' }
          },
          {
            value: data.good,
            name: '良好',
            itemStyle: { color: '#b9c000' }
          },
          {
            value: data.pass,
            name: '合格',
            itemStyle: { color: '#fc9802' }
          },
          {
            value: data.fail,
            name: '不合格',
            itemStyle: { color: '#ff520d' }
          }
        ].filter(item => item.value > 0);
      };

      // 处理无数据情况
      if (peopleData.total === 0) {
        this.passRateChart.setOption({
          graphic: {
            type: 'text',
            left: 'center',
            top: 'middle',
            style: {
              text: '暂无合格率数据',
              fill: '#fff',
              fontSize: 16
            }
          }
        });
        return;
      }

      // 准备图表类型数据
      const chartTypes = [
        {
          key: 'total',
          title: '总体',
          ...{ data: prepareData(scoreData.total) },
          show: peopleData.total > 0,
          row: 1
        },
        {
          key: 'male',
          title: '男性',
          ...{ data: prepareData(scoreData.male) },
          show: peopleData.male > 0,
          row: 2
        },
        {
          key: 'female',
          title: '女性',
          ...{ data: prepareData(scoreData.female) },
          show: peopleData.female > 0,
          row: 2
        }
      ].filter(type => type.show);

      // 计算行数和每行图表数
      const row1Charts = chartTypes.filter(type => type.row === 1);
      const row2Charts = chartTypes.filter(type => type.row === 2);
      const totalRows = (row1Charts.length > 0 ? 1 : 0) + (row2Charts.length > 0 ? 1 : 0);

      // 当只有两个图表时强制分配到同一行
      if (chartTypes.length === 2) {
        chartTypes.forEach(type => {
          type.row = 1;
        });
        // 重新计算行数
        const newRow1Charts = chartTypes.filter(type => type.row === 1);
        const newRow2Charts = chartTypes.filter(type => type.row === 2);
        row1Charts.length = 0;
        row1Charts.push(...newRow1Charts);
        row2Charts.length = 0;
        row2Charts.push(...newRow2Charts);
      }

      // 样式配置
      const color = ['#69af35', '#b9c000', '#fc9802', '#ff520d'];
      const colorBorder = ['rgba(105,175,53,0.65)', 'rgba(185,192,0,0.65)', 'rgba(252,152,2,0.65)', 'rgba(255,82,13,0.65)'];

      // 准备系列和图形元素
      const series = [];
      const graphicElements = [];

      // 计算位置 - 完整优化版本
      const calculatePositions = (charts, rowNumber) => {
        const activeRows = [];
        if (row1Charts.length > 0) activeRows.push(1);
        if (row2Charts.length > 0) activeRows.push(2);
        const rowCount = activeRows.length;
        if (rowCount === 0) return [];

        const rowIndex = activeRows.indexOf(rowNumber);
        if (rowIndex === -1) return [];

        // 动态计算行高和位置
        let top;
        if (rowCount === 1) {
          // 只有一行时，居中显示
          top = 50;
        } else {
          // 多行时，增加行间距
          const rowSpacing = 20; // 增加行间距
          const rowHeight = (100 - rowSpacing) / rowCount;
          top = rowIndex * (rowHeight + (rowSpacing / rowCount)) + rowHeight / 2;
        }

        const chartCount = charts.length;
        const positions = [];
        const containerWidth = this.$refs.passRateChart.offsetWidth;

        // 动态调整水平间距
        let baseSpacing;
        if (rowCount === 1) {
          if (chartCount === 1) {
            baseSpacing = 0; // 只有一个饼图，居中
          } else if (chartCount === 2) {
            // 一行2个饼图，增加间距
            baseSpacing = containerWidth > 800 ? 55 : 45;
          } else {
            baseSpacing = containerWidth > 800 ? 30 : 20;
          }
        } else {
          baseSpacing = containerWidth > 800 ? 40 : 30;
        }

        if (chartCount === 1) {
          positions.push({ x: 50, y: top });
        } else if (chartCount === 2) {
          positions.push({ x: 50 - baseSpacing / 2, y: top });
          positions.push({ x: 50 + baseSpacing / 2, y: top });
        } else if (chartCount === 3) {
          positions.push({ x: 25, y: top });
          positions.push({ x: 50, y: top });
          positions.push({ x: 75, y: top });
        }

        return positions;
      };

      // 动态计算饼图大小 - 完整优化版本
      const calculateRadius = () => {
        const containerWidth = this.$refs.passRateChart.offsetWidth;
        const containerHeight = this.$refs.passRateChart.offsetHeight;

        // 根据具体情况调整饼图大小
        let sizeFactor;
        const totalCharts = row1Charts.length + row2Charts.length;

        if (totalRows === 1) {
          if (totalCharts === 2) {
            // 一行2个饼图 - 最大尺寸
            sizeFactor = 0.22;
          } else if (totalCharts === 1) {
            // 一行1个饼图 - 较大尺寸
            sizeFactor = 0.25;
          } else {
            // 一行3个饼图 - 中等尺寸
            sizeFactor = 0.16;
          }
        } else {
          // 多行情况 - 较小尺寸
          sizeFactor = totalCharts === 3 ? 0.16 : 0.18;
        }

        const baseSize = Math.min(containerWidth, containerHeight) * sizeFactor;

        // 根据饼图数量调整内圈半径
        const innerRadiusRatio = totalCharts <= 2 ? 0.5 : 0.6; // 饼图少时更饱满

        return [baseSize * innerRadiusRatio, baseSize];
      };

      // 渲染图表
      const renderChart = (type, centerX, centerY, radius) => {
        const totalValue = type.data.reduce((sum, item) => sum + item.value, 0);
        const maxValue = Math.max(...type.data.map(item => item.value));

        const qualifiedValue = type.data.reduce((sum, item) => {
          return item.name !== '不合格' ? sum + item.value : sum;
        }, 0);
        const qualifiedRate = totalValue > 0 ? (qualifiedValue / totalValue * 100).toFixed(1) + '%' : '0%';

        const chartData = type.data.map((item, i) => {
          const colorIndex = ['优秀', '良好', '合格', '不合格'].indexOf(item.name);
          return {
            value: item.value,
            name: item.name,
            itemStyle: {
              color: color[colorIndex],
              borderWidth: 3,
              borderColor: '#fff',
              shadowColor: 'rgba(0, 0, 0, 0.2)',
              shadowBlur: 6,
              shadowOffsetY: 4
            }
          };
        });

        series.push({
          name: type.title,
          type: 'pie',
          radius: ['19%', '39%'],
          center: [`${centerX}%`, `${centerY}%`],
          label: {
            color: '#fff',
            lineHeight: 14,
            formatter: e => {
              return `${e.name}\n${e.value} (${((e.value / totalValue) * 100).toFixed(1)}%)`;
            }
          },
          labelLine: {
            length: 20,
            lineStyle: {
              color: '#999'
            }
          },
          data: chartData
        });

        graphicElements.push({
          type: 'group',
          left: `${centerX - 2}%`,
          top: `${centerY - 4}%`,
          children: [{
            type: 'text',
            z: 100,
            left: 'center',
            top: -20,
            style: {
              text: type.title,
              fill: '#fff',
              font: '14px Microsoft YaHei',
              textAlign: 'center'
            }
          }, {
            type: 'text',
            z: 100,
            left: 'center',
            top: 10,
            style: {
              text: qualifiedRate,
              fill: '#fff',
              font: '20px Microsoft YaHei',
              textAlign: 'center',
              fontWeight: 'bold'
            }
          }]
        });
      }

      // 渲染行1图表
      const row1Positions = calculatePositions(row1Charts, 1);
      const radius = calculateRadius();
      row1Charts.forEach((type, index) => {
        renderChart(type, row1Positions[index].x, row1Positions[index].y, radius);
      });

      // 渲染行2图表
      const row2Positions = calculatePositions(row2Charts, 2);
      row2Charts.forEach((type, index) => {
        renderChart(type, row2Positions[index].x, row2Positions[index].y, radius);
      });

      // 处理无数据情况
      if (series.length === 0) {
        this.passRateChart.setOption({
          graphic: {
            type: 'text',
            left: 'center',
            top: 'middle',
            style: {
              text: '暂无合格率数据',
              fill: '#fff',
              fontSize: 16
            }
          }
        });
        return;
      }

      // 图表配置
      const option = {
        backgroundColor: 'transparent',
        legend: {
          right: 10,
          show: true,
          orient: 'vertical',
          itemGap: 10,
          borderWidth: 0, // 明确去除边框
          textStyle: {
            color: '#fff',
            fontSize: 12 // 保持与右侧一致
          },
          itemStyle: {
            borderWidth: 0 // 去除图例项边框
          },
        },
        series: series,
        graphic: graphicElements
      };

      // 应用配置
      this.passRateChart.setOption(option, true);
      this.passRateChart.resize();
    },

    /** 渲染合并统计图表（保持不变） */
    renderCombinedChart() {
      if (!this.combinedChart) return;

      this.combinedChart.clear();
      this.hasGoodLevel = false;

      const scoreData = this.chartData.scoreDistributionData || {
        male: {}, female: {}, total: {}
      };
      const peopleData = this.chartData.peopleData || { male: 0, female: 0, total: 0 };

      const hasMaleData = peopleData.male > 0;
      const hasFemaleData = peopleData.female > 0;

      const hasGoodData =
        (scoreData.male.good || 0) > 0 ||
        (scoreData.female.good || 0) > 0;

      const levelConfigs = [
        {
          name: '优秀',
          color: '#69AF35',
          borderColor: '#49921c',
          legendColor: '#69AF35'
        },
        ...(hasGoodData ? [{
          name: '良好',
          color: '#D5E731',
          borderColor: '#FFFC35',
          legendColor: '#D5E731'
        }] : []),
        {
          name: '合格',
          color: '#FC9802',
          borderColor: '#FF530B',
          legendColor: '#FC9802'
        },
        {
          name: '不合格',
          color: 'rgba(255,82,13)',
          borderColor: '#e26838',
          legendColor: 'rgba(255,82,13)'
        }
      ].map(config => ({
        ...config,
        getData: (data) => [
          data.total[config.name === '优秀' ? 'excellent' :
            config.name === '良好' ? 'good' :
              config.name === '合格' ? 'pass' : 'fail'] || 0,
          hasMaleData ? (data.male[config.name === '优秀' ? 'excellent' :
            config.name === '良好' ? 'good' :
              config.name === '合格' ? 'pass' : 'fail'] || 0) : null,
          hasFemaleData ? (data.female[config.name === '优秀' ? 'excellent' :
            config.name === '良好' ? 'good' :
              config.name === '合格' ? 'pass' : 'fail'] || 0) : null
        ].filter(v => v !== null)
      }));

      const xAxisData = ['总计'];
      if (hasMaleData) xAxisData.push('男性');
      if (hasFemaleData) xAxisData.push('女性');

      const totalValues = [peopleData.total];
      if (hasMaleData) totalValues.push(peopleData.male);
      if (hasFemaleData) totalValues.push(peopleData.female);

      if (xAxisData.length === 1 && totalValues[0] === 0) {
        this.combinedChart.setOption({
          graphic: {
            type: 'text',
            left: 'center',
            top: 'middle',
            style: {
              text: '暂无统计数据',
              fill: '#fff',
              fontSize: 16
            }
          }
        });
        return;
      }

      const seriesData = levelConfigs.map(level => ({
        name: level.name,
        type: 'bar',
        stack: 'total',
        barWidth: 60,
        emphasis: { focus: 'series' },
        data: level.getData(scoreData),
        itemStyle: {
          color: {
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            type: 'linear',
            global: false,
            colorStops: [
              { offset: 0, color: level.color },
              { offset: 1, color: level.color }
            ]
          },
          borderColor: level.borderColor,
          borderWidth: 1,
          borderRadius: 0,
          shadowBlur: 0,
          shadowColor: 'transparent',
          shadowOffsetY: 0
        },
        label: {
          show: true,
          position: 'right',
          distance: 10,
          formatter: '{c}',
          color: '#fff',
          fontSize: 12,
          fontWeight: 'bold'
        }
      }));

      const maxValue = Math.max(...totalValues);
      const maxlen = Math.pow(10, String(Math.ceil(maxValue)).length - 2);
      const maxY = maxValue >= 5 ? Math.ceil(maxValue / (10 * maxlen)) * maxlen * 10 : 5;

      const generateDiamondDecorations = () => {
        const decorations = [];
        const barWidth = 60;
        const diamondWidth = barWidth - 2;
        const diamondHeight = 15;

        const levelAccumulations = [];
        xAxisData.forEach((_, categoryIndex) => {
          let accumulation = 0;
          const categoryAccumulations = [];
          levelConfigs.forEach(level => {
            const value = level.getData(scoreData)[categoryIndex] || 0;
            accumulation += value;
            categoryAccumulations.push(accumulation);
          });
          levelAccumulations.push(categoryAccumulations);
        });

        levelConfigs.forEach((level, levelIndex) => {
          const bottomDiamondData = xAxisData.map((_, categoryIndex) => {
            const isFirstVisibleLevel = levelIndex === 0 ||
              levelConfigs.slice(0, levelIndex).every(
                (l, i) => l.getData(scoreData)[categoryIndex] === 0
              );
            const value = level.getData(scoreData)[categoryIndex] || 0;
            return isFirstVisibleLevel && value > 0 ? 0 : null;
          });

          decorations.push({
            type: 'pictorialBar',
            symbol: 'diamond',
            symbolSize: [diamondWidth, diamondHeight],
            symbolOffset: [0, diamondHeight / 2],
            symbolPosition: 'start',
            zlevel: 3 + levelIndex,
            silent: true,
            data: bottomDiamondData,
            itemStyle: {
              color: level.color,
              shadowBlur: 0,
              shadowColor: 'transparent'
            },
            barWidth: barWidth,
            barGap: '-100%',
            barCategoryGap: '0%'
          });
        });

        levelConfigs.forEach((level, levelIndex) => {
          const topDiamondData = xAxisData.map((_, categoryIndex) => {
            const value = level.getData(scoreData)[categoryIndex] || 0;
            return value > 0 ? levelAccumulations[categoryIndex][levelIndex] : null;
          });

          decorations.push({
            type: 'pictorialBar',
            symbol: 'diamond',
            symbolSize: [diamondWidth, diamondHeight],
            symbolOffset: [0, -diamondHeight / 2],
            symbolPosition: 'end',
            zlevel: 4 + levelIndex,
            silent: true,
            data: topDiamondData,
            itemStyle: {
              color: level.borderColor,
              shadowBlur: 0,
              shadowColor: 'transparent'
            },
            barWidth: barWidth,
            barGap: '-100%',
            barCategoryGap: '0%'
          });
        });

        return decorations;
      };

      const option = {
        backgroundColor: 'transparent',
        animation: false,
        tooltip: {
          trigger: 'axis',
          className: 'custom-echarts-tooltip',
          axisPointer: { type: 'shadow' },
          formatter: (params) => {
            // 过滤有效参数：排除"总数"系列、象形柱系列和值为0的数据
            const activeParams = params.filter(p =>
              p.seriesName !== '总数' &&
              p.componentSubType !== 'pictorialBar' &&
              p.value > 0
            );

            if (activeParams.length === 0) return '';

            const date = params[0].axisValue;
            const currentTotal = totalValues[params[0].dataIndex];

            return `
      <div class="tooltip-title">${date}</div>
      ${activeParams.map(p => {
              const percent = currentTotal > 0 ? (p.value / currentTotal * 100).toFixed(1) : '0.0';
              return `
          <div class="tooltip-item">
            <span class="tooltip-marker" style="background: ${p.color}"></span>
            <span>${p.seriesName}: ${p.value.toLocaleString()} (${percent}%)</span>
          </div>
        `;
            }).join('')}
      <div class="tooltip-total">总计: ${currentTotal.toLocaleString()}</div>
    `;
          }
        },
        legend: {
          borderWidth: 0,
          orient: 'vertical',
          data: levelConfigs.map(level => ({
            name: level.name,
            icon: 'roundRect',
            itemStyle: {
              color: level.legendColor,
              borderColor: 'none'
            }
          })),
          right: 10,
          textStyle: {
            color: '#fff',
          },
        },
        grid: {
          left: '13%',
          right: '14%',
          top: '15%',
          bottom: '5%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLine: {
            show: true,
            lineStyle: { color: '#fff' }
          },
          axisLabel: {
            color: '#fff',
            fontSize: 12
          }
        },
        yAxis: {
          type: 'value',
          name: '人数',
          nameTextStyle: {
            color: '#fff'
          },
          minInterval: 1,
          min: 0,
          max: maxY,
          axisLine: {
            show: false,
            lineStyle: { color: '#fff' }
          },
          axisLabel: {
            color: '#fff',
            fontSize: 12
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: 'transparent'
            }
          }
        },
        series: [
          {
            name: '总数',
            type: 'bar',
            barWidth: '60%',
            barGap: '-100%',
            itemStyle: { color: 'transparent' },
            label: {
              show: true,
              position: 'top',
              rich: {
                total: {
                  align: 'center',
                  verticalAlign: 'bottom',
                  color: '#fff',
                  fontSize: 14,
                  fontWeight: 'bold',
                  width: '100%'
                }
              },
              formatter: function(params) {
                return `{total|${totalValues[params.dataIndex]}}`;
              }
            },
            data: totalValues.map(value => ({
              value,
              labelLayout: {
                x: '50%',
                y: 0,
                align: 'center'
              }
            })),
            z: 1
          },
          ...seriesData,
          ...generateDiamondDecorations()
        ]
      };

      this.combinedChart.setOption(option, true);
      this.combinedChart.resize();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.$refs.queryForm.validate(valid => {
        if (valid) {
          this.showCharts = true;
          this.loading = true;

          setTimeout(() => {
            this.loading = false;
            this.$nextTick(() => {
              this.initCharts();
            });
          }, 500);

          let queryParams = {
            deptid: this.form.deptId,
            starttime: this.form.starttime,
            endtime: this.form.endtime,
            year: this.form.starttime.split("-")[0],
            item: this.form.testItem,
            ageMin: this.form.ageMin,
            ageMax: this.form.ageMax,
          }

          getItemevalution(queryParams).then(response => {
            const maleSum = Object.entries(response)
              .filter(([key]) => key.startsWith('man'))
              .reduce((sum, [, value]) => sum + value, 0);
            this.chartData.peopleData.male = maleSum;

            const femaleSum = Object.entries(response)
              .filter(([key]) => key.startsWith('woman'))
              .reduce((sum, [, value]) => sum + value, 0);
            this.chartData.peopleData.female = femaleSum;

            const total = maleSum + femaleSum;
            this.chartData.peopleData.total = total;

            this.chartData.passRateData.male = (
              (maleSum - response.manunqualifiedllvalue) / maleSum * 100
            ).toFixed(1);

            this.chartData.passRateData.female = (
              (femaleSum - response.womanunqualifiedllvalue) / femaleSum * 100
            ).toFixed(1);

            const qualifiedllvalue = total - (response.manunqualifiedllvalue + response.womanunqualifiedllvalue);
            this.chartData.passRateData.total = (qualifiedllvalue / total * 100).toFixed(1);

            this.chartData.scoreDistributionData.male.excellent = response.mannicevalue;
            this.chartData.scoreDistributionData.male.good = response.mangoodllvalue;
            this.chartData.scoreDistributionData.male.pass = response.manqualifiedllvalue;
            this.chartData.scoreDistributionData.male.fail = response.manunqualifiedllvalue;

            this.chartData.scoreDistributionData.female.excellent = response.womannicevalue;
            this.chartData.scoreDistributionData.female.good = response.womangoodllvalue;
            this.chartData.scoreDistributionData.female.pass = response.womanqualifiedllvalue;
            this.chartData.scoreDistributionData.female.fail = response.womanunqualifiedllvalue;

            this.chartData.scoreDistributionData.total.excellent = response.mannicevalue + response.womannicevalue;
            this.chartData.scoreDistributionData.total.good = response.mangoodllvalue + response.womangoodllvalue;
            this.chartData.scoreDistributionData.total.pass = response.manqualifiedllvalue + response.womanqualifiedllvalue;
            this.chartData.scoreDistributionData.total.fail = response.manunqualifiedllvalue + response.womanunqualifiedllvalue;

            this.renderAllCharts();
            this.lastQueryParams = this.currentQueryParams;
          });
        }
      });
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.form = {
        deptId: undefined,
        dateRange: null,
        population: undefined,
        testItem: undefined,
        starttime: undefined,
        endtime: undefined
      };
      this.selectedNodeInfo = '';
      this.showCharts = false;
      this.testItemOptions = [];
      this.leftTestItems = [];
      this.rightTestItems = [];
      this.selectedPeopleType = '幼儿'; // 重置时默认选中幼儿
      this.lastQueryParams = null;
      this.$refs.tree.setCurrentKey(null);
      this.$nextTick(() => {
        this.$refs.queryForm.clearValidate();
      });

      this.autoQueryTriggered = false;
      if (this.queryTimer) {
        clearTimeout(this.queryTimer);
        this.queryTimer = null;
      }

      if (this.passRateChart) {
        this.passRateChart.dispose();
        this.passRateChart = null;
      }
      if (this.combinedChart) {
        this.combinedChart.dispose();
        this.combinedChart = null;
      }

      Object.values(this.resizeObservers).forEach(observer => {
        observer.disconnect();
      });
      this.resizeObservers = {};
    },

    /** 处理窗口大小变化 */
    handleWindowResize() {
      if (this.passRateChart) {
        this.passRateChart.resize();
        this.renderPassRateChart(); // 重新渲染饼图以适应新尺寸
      }
      if (this.combinedChart) {
        this.combinedChart.resize();
      }
    }
  },
  mounted() {
    // 添加窗口大小变化监听器
    this.windowResizeHandler = () => this.handleWindowResize();
    window.addEventListener('resize', this.windowResizeHandler);
  },
  beforeDestroy() {
    if (this.passRateChart) {
      this.passRateChart.dispose();
      this.passRateChart = null;
    }
    if (this.combinedChart) {
      this.combinedChart.dispose();
      this.combinedChart = null;
    }

    Object.values(this.resizeObservers).forEach(observer => {
      observer.disconnect();
    });

    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
    }

    if (this.queryTimer) {
      clearTimeout(this.queryTimer);
    }

    // 移除窗口大小变化监听器
    if (this.windowResizeHandler) {
      window.removeEventListener('resize', this.windowResizeHandler);
    }
  },
  created() {
    this.getDeptTree();
    this.getPopulationTypes();
  }
};
</script>

<style scoped lang="scss">
.app-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: hidden;
  background: url('../../assets/images/bgn.png');
  background-size: 100% 100%;
  padding: 16px;
  box-sizing: border-box;
  /*padding-top: 0;*/
}

.main-container {
  position: relative;
  width: 100%;
  overflow: hidden;
}

/* 左侧面板样式 */
.left-panel {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background-color: #0160FA;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  z-index: 10;
  transition: width 0.3s ease;
  overflow: auto;
  padding: 16px;
  box-sizing: border-box;
}

.left-panel.hidden {
  width: 0 !important;
  padding: 0;
}

/* 右侧面板样式 */
.right-panel {
  width: 100%;
  height: 100%;
  padding-left: 0;
  transition: padding-left 0.3s ease;
  box-sizing: border-box;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

/* 切换按钮样式 */
.toggle-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 10px;
  height: 30px;
  background-color: rgba(0,128,255,0.3);
  border: 1px solid #0080ff;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  z-index: 20;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: left 0.3s ease;
}

.toggle-btn i {
  color: #fff;
  font-size: 10px;
}

.indicatorbtm{
  background: url('../../assets/images/indicatorbtm.png');
  background-size: 100% 100%;
}

/* 表单样式调整 */
.custom-form {
  .el-form-item {
    margin-right: 20px;
    margin-bottom: 18px;
  }

  .el-form-item__label {
    white-space: nowrap;
    padding-right: 8px;
    color: #fff!important;
  }
  ::v-deep .el-form-item__label {
    color: #fff;

  }
  .el-input, .el-select, .el-date-editor {
    width: 220px;
  }

  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 260px;
    height: 36px!important;
    line-height: 36px!important;
  }
}
::v-deep .custom-form .el-input__inner {
  height: 36px!important;
  line-height: 36px!important;
}
/* 图表区域样式优化 */
.chart-container {
  margin-top: 0px;
  margin-bottom: 20px;
  padding: 20px;
  background-color: transparent;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
 /* background: url('../../assets/images/chart-container906.png');*/
  background: url('../../assets/images/chart-container1024.png');
  background-size: 100% 100%;
}

.full-height {
  height: 100%;
}

.chart-wrapper {
  padding: 16px;
  border-radius: 4px;
  /* border: 2px solid #00afff;*/
  display: flex;
  flex-direction: column;
  min-height: 0;
  position: relative;
}

.chart-title {
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #fff;
  flex-shrink: 0;
}

.chart {
  position: absolute;
  top: 40px;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  height: calc(100% - 40px);
}

/* 人群分类样式 */
.people-type-item {
  width: 46px;
  height: 46px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  color: white;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
}

.people-type-item.active {
  //background-color: rgba(255, 255, 255, 0.3);
  //border-radius: 8px;
  //font-weight: bold;
  transform: scale(1.1);
}

/* 测试项目样式 */
.test-item {
  width: 44px;//69
  height:40px;//62
  margin: 0 5px;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.test-item.active {
  transform: scale(1.1);
  /*box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);*/
}

/* 工具提示样式 */
.test-item-tooltip {
  position: fixed;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
  pointer-events: none;
  z-index: 9999;
  transform: translateY(-100%);
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .custom-form .el-form-item {
    margin-right: 15px;
    margin-bottom: 15px;
  }

  .el-col {
    padding: 0 10px !important;
  }
}

@media (max-width: 992px) {
  .chart-container {
    padding: 15px;
  }

  .chart-wrapper {
    padding: 12px;
  }
}

@media (max-width: 768px) {
  .custom-form .el-form-item {
    display: block;
    margin-right: 0;
    width: 100%;

    .el-form-item__content {
      width: 100%;
    }

    .el-input, .el-select, .el-date-editor {
      width: 100% !important;
    }
  }

  .chart-container .el-col {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }

  .left-panel {
    width: 30% !important;
  }

  .test-item {
    width: 50px;
    height: 45px;
  }
}
/* 美化 el-input 输入框 */
::v-deep .el-input .el-input__inner {
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid #00CCFE;
  border-radius: 6px;
  color: #f0f0f0;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
  font-size: 14px;
}

/* 输入框 placeholder 颜色改为 #fff */
::v-deep .el-input__inner::placeholder {
  color: #fff !important;
}

/* 输入框获得焦点时边框高亮 */
::v-deep .el-input .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.6);
  background-color: rgba(255, 255, 255, 0.15);
  color: #fff;
}

/* 搜索区按钮美化 - 调大尺寸 */
::v-deep .el-form-item .el-button {
  border-radius: 22px;
  font-weight: 600;
  font-size: 15px;
  padding: 10px 28px;
  transition: all 0.3s ease;
  box-shadow: 0 3px 8px rgba(66, 133, 244, 0.3);
}

///* 搜索按钮（主按钮） */
//::v-deep .el-form-item .el-button--primary {
//  background: linear-gradient(45deg, #409eff, #66b1ff);
//  border: none;
//  color: #fff;
//  box-shadow: 0 5px 14px rgba(64, 158, 255, 0.6);
//}
//
//::v-deep .el-form-item .el-button--primary:hover {
//  background: linear-gradient(45deg, #66b1ff, #409eff);
//  box-shadow: 0 7px 18px rgba(64, 158, 255, 0.8);
//}


/* 美化日期选择框 */
::v-deep .el-date-editor {
  background-color: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid #00CCFE !important;
  border-radius: 6px;
  color: #f0f0f0 !important;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

::v-deep .el-date-editor:hover {
  border-color: #409eff !important;
}

::v-deep .el-date-editor .el-range-input {
  background-color: transparent !important;
  color: #fff !important;
}

::v-deep .el-date-editor .el-range-separator {
  color: rgba(255, 255, 255, 0.8) !important;
}

/* 日期选择框 placeholder 颜色改为白色 */
::v-deep .el-date-editor .el-range-input::placeholder {
  color: #fff !important;
}

/* 单个日期选择框（非范围） placeholder 颜色 */
::v-deep .el-date-editor input::placeholder {
  color: #fff !important;
}
/* 树机构样式修改  */
::v-deep .el-tree {
  background: #0080FF;
  color: #fff;
  border-radius: 8px;
}
::v-deep .el-tree-node__content:hover {
  background-color: #0879e9;
}
::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #0879e9;
}

/*css主要部分的样式*/
/*定义滚动条宽高及背景，宽高分别对应横竖滚动条的尺寸*/
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

/*定义滚动条的轨道颜色、内阴影及圆角*/
::-webkit-scrollbar-track{
  border-radius: 4px;
  background-color: rgb(1 96 250);
}

/*定义滑块颜色、内阴影及圆角*/
::-webkit-scrollbar-thumb{
  border-radius: 8px;
  background-color: #0080ff;
}

/*定义滑块悬停变化颜色、内阴影及圆角*/
::-webkit-scrollbar-thumb:hover{
  background-color: #C7C9CC;
}
::v-deep {

  .is-horizontal {
    height: 0px;
    left: 0px;
    display: none;
  }

}

/* 调整表单里的按钮间距 */
::v-deep .el-form-item .el-button {
  margin-left: 12px; /* 你可以改成 16px 更宽松 */
}
/* 按钮通用样式（不改尺寸） */
::v-deep .el-form-item .action-btn {
  border-radius: 20px; /* 圆润 */
  font-weight: 600;
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
}

/* 悬浮时按钮微微上浮 + 光晕 */
::v-deep .el-form-item .action-btn:hover {
  transform: translateY(-2px);
}

/* 搜索按钮 - 宝石蓝渐变 */
::v-deep .el-form-item .search-btn {
  background: linear-gradient(135deg, #b4cdeb, #2f6bcc);
  color: #fff;
}
::v-deep .el-form-item .search-btn:hover {
  background: linear-gradient(135deg, #5aa2f8, #3a8ef6);
  box-shadow: 0 6px 14px rgba(58, 142, 246, 0.5);
}

/* 重置按钮 - 高级灰蓝 */
::v-deep .el-form-item .reset-btn {
  background: linear-gradient(135deg, #df9f3f, #edc73d);
  color: #fff;
}
::v-deep .el-form-item .reset-btn:hover {
  background: linear-gradient(135deg, #ffcc80, #ffb74d);
  box-shadow: 0 6px 14px rgba(255, 183, 77, 0.5);
}
</style>
